package com.cloudcentral.filter;

import com.cloudcentral.exception.FailureException;
import com.cloudcentral.util.VerifyUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.redisson.api.RedissonClient;
import org.springframework.http.HttpMethod;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

import static com.cloudcentral.util.Utils.errorMessage;

/**
 * Create by Administrator
 * 2023/11/10 9:40
 */
public class CaptchaVerifyFilter extends GenericFilter {
  private final RedissonClient redissonClient;

  public CaptchaVerifyFilter(RedissonClient redissonClient) {
    this.redissonClient = redissonClient;
  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
    if (requestMatcher((HttpServletRequest) request, "/login")) {
      try {
        String captchaId = request.getParameter("captchaId"), captcha = request.getParameter("captcha");
        if (VerifyUtils.captcha(redissonClient, captchaId, captcha)) chain.doFilter(request, response);
      } catch (FailureException e) {
        ((HttpServletResponse) response).sendRedirect("/login.html?error=" + URLEncoder.encode(errorMessage(e), StandardCharsets.UTF_8));
        //WebUtils.writeJson(response, Result.failure(errorMessage(e)));
      }
    } else {
      chain.doFilter(request, response);
    }
  }

  private boolean requestMatcher(HttpServletRequest request, String... patterns) {
    return Arrays.stream(patterns).map(item -> AntPathRequestMatcher.antMatcher(HttpMethod.POST, item)).anyMatch(item -> item.matches(request));
  }
}
